// pages/square/square.js
var app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        shoppingList:[],
        recommandList:[],
        addressList:[],
        sumPrice:Number(0),
        allSelect: 0,
        nums:0,
        currentTab: 0,   /*初始显示的页面*/
    },
    ///修改默认地址(点击事件)
    boult:function(){
      wx.navigateTo({
        url: '/pages/mine/mine',
      })
    },

    ///点击结算
    amount(e){
      if(this.data.addressList.length){
        if(wx.getStorageSync('nums') > 0) {
          wx.navigateTo({
            url: '/pages/amount/amount'
          })
        } else {
          wx.showToast({
            title: '还未选择需要购买的商品',
            icon:'none'
          })
        }
      } else {
        wx.showModal({
          title:'购买提示',
          content: '请先选择收货地址',
          showCancel:false,
          success (res) {
            if (res.confirm){
              wx.navigateTo({
                url: '/pages/mine/mine',
              })
            }
          }
        })
      }
    },
    ///获取默认地址信息
    getAddressList(){
      wx.get('http://localhost:8000/wx/shopping/address').then(res => {
        this.setData({
          addressList:res
        })
      })
    },
    ///获取购物车信息
    getShoppingList(){
      // 获取购物车已选商品信息
      let cart = wx.getStorageSync('cart') || []
      let allSelect = wx.getStorageSync('allSelect')
      let sumPrice = Number(0)
      let nums = 0
      // console.log("页面初始化前价格："+sumPrice+"，数量："+nums)
       //获取购物车数据
       wx.get('http://localhost:8000/wx/shoppingDetail?memberId='+wx.getStorageSync('userInfo')._id).then(res => {
        // 根据勾选的数据与购物车商品数据来判断是否全选
        if(cart.length !== 0 && res.data.length===cart.length){
          allSelect = 1
        }else{
          allSelect = 0
        }
        // 循环处理是否被勾选
        res.data.forEach(a => {
          cart.forEach(b=>{
            if(a.id===b){
              a.isChecked=1
              nums += a.num
              sumPrice += Number(a.price)*Number(a.num)
            }
          })
        });

        // console.log("页面初始化后价格："+sumPrice+"，数量："+nums)
        wx.setStorageSync('allSelect', allSelect)
        wx.setStorageSync('nums', nums)
        wx.setStorageSync('sumPrice', sumPrice)
         this.setData({
          shoppingList:res.data,
          sumPrice: Number(sumPrice.toFixed(2)),
          nums:nums,
          allSelect: allSelect
         })
       })
      },
      ///获取为你推荐信息
      getRecommandList(){
        wx.get('http://localhost:8000/wx/recommand').then(res => {
        //   console.log(res)
          this.setData({
            recommandList:res
          })
        })
      },

      //点击商品跳转商品详情页面
      toDetail(e){
        wx.navigateTo({
            url: '/pages/details/details?id=' + e.currentTarget.dataset.detail.shoppingId + '&type=' + (e.currentTarget.dataset.detail.shoppingType - 1)
        })
      },

      ///为你推荐跳转页面事件
      recommand(e){
        // console.log(e)
        // let id = e.currentTarget.dataset.id
        wx.navigateTo({
          url: '/pages/recommand/recommand?id=' + e.currentTarget.dataset.id,
        })
      },
      radiocon:function(e){
        var check = this.data.check;
          check =! check;
          this.setData({
            check:check
          })
      },

      ///选择商品(单选)
      selectGood(e){
        //获取购物车列表
        let cart = wx.getStorageSync('cart') || [];
        // // 获取购物车全选状态
        // let allSelect = wx.getStorageSync('allSelect') || 0;
        // // 获取合计价格
        // let sumPrice = Number(wx.getStorageSync('sumPrice') || 0);
        // let nums = wx.getStorageSync('nums') || 0
        // 获取当前选择商品
        let good = e.currentTarget.dataset.good;
        let index = cart.indexOf(good.id)
        if(index===-1){
          console.log("勾选")
          cart.push(good.id)
          // sumPrice += Number(good.price)*Number(good.num)
          // nums += good.num
        }else{
          console.log("取消勾选")
          cart.splice(index,1)
          // allSelect = 0
          // this.data.allSelect = 0
          // sumPrice -= Number(good.price)*good.num
          // nums -= good.num
        }
        // this.setData({
          // sumPrice: Number(sumPrice),
          // nums: nums
        //  })
        wx.setStorageSync('cart', cart)
        // wx.setStorageSync('allSelect', allSelect)
        // wx.setStorageSync('sumPrice', Number(sumPrice))
        // wx.setStorageSync('nums', nums)
        this.getShoppingList()
      },
      /**
     * 删除购物车
     */
    deleteGood(e){
      let that = this
      wx.showModal({
        title: '确定删除该商品吗',
        success(res) {
          if (res.confirm) {
            let cart = wx.getStorageSync('cart')
            wx.get('http://localhost:8000/wx/delShopping?id='+e.currentTarget.dataset.good.id).then(res => {
              console.log(res)
              if(res.code===200){
                let index = cart.indexOf(e.currentTarget.dataset.good.id)
                if(index !== -1){
                  cart.splice(index,1)
                  wx.setStorageSync('cart', cart)
                }
                that.getShoppingList()
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000
                })
              }else{
                wx.showToast({
                  title: '删除失败',
                  icon: 'error',
                  duration: 2000
                })
              }
               
            })
            
          }
        }
      })
    },

    ///减少商品数量
    decreaseNum(e){
      if(e.currentTarget.dataset.good.num <= 1){
          wx.showToast({
            title: '该宝贝不能在减少了哦~',
            icon:'none'
          })
      }else{
        let nums = wx.getStorageSync('nums') || 0
        let sumPrice = wx.getStorageSync('sumPrice')
        let cart = wx.getStorageSync('cart') || []
        wx.get('http://localhost:8000/wx/shoppingDelOne?id='+e.currentTarget.dataset.good.id).then(res => {
          this.getShoppingList();
        })
      }
    },

    ///增加商品数量
    addNum(e){
      let nums = wx.getStorageSync('nums') || 0
      let sumPrice = wx.getStorageSync('sumPrice')
      console.log("添加数量前价格："+sumPrice+"，数量："+nums)
      let cart = wx.getStorageSync('cart') || []
      wx.get('http://localhost:8000/wx/shoppingAddOne?id='+e.currentTarget.dataset.good.id).then(res => {
        this.getShoppingList();
      })
      
      },

      ///清理商品选择状态
      changeIsCheckedFalse(){
        // 清理购物车相关缓存
        wx.removeStorageSync('cart')
        wx.removeStorageSync('sumPrice')
        wx.removeStorageSync('allSelect')
        wx.removeStorageSync('nums')
      },

      ///全选
      allSelectgood(e){
        let cart = [];
        let sumPrice = 0.00
        let nums = 0
        let allSelect = wx.getStorageSync('allSelect') || 0
        let shoppingList = this.data.shoppingList
        if(allSelect){
          allSelect = 0
          console.log('取消全选');
          /**
           * 1、修改购物车数据勾选状态；
           * */
          shoppingList.forEach(e=>{
            e.isChecked=0
          })
        //全选
        }else{
          console.log('全选');
          allSelect = 1;
          /**
           * 1、修改购物车数据勾选状态；
           * 2、统计商品数量
           * 3、统计商品合计价格
           * */
          shoppingList.forEach(e=>{
            cart.push(e.id)
            e.isChecked=1
            nums += e.num
            sumPrice += Number(e.price)*Number(e.num)
          })
        }
        console.log("全选状态:"+allSelect)
        wx.setStorageSync('cart', cart)
        wx.setStorageSync('nums', nums)
        wx.setStorageSync('sumPrice', sumPrice)
        wx.setStorageSync('allSelect', allSelect)
        this.setData({
          shoppingList:shoppingList,
          nums:nums,
          sumPrice:Number(sumPrice),
          allSelect:allSelect
        })
      },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getShoppingList();
        this.getRecommandList();
        this.getAddressList();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {   //页面显示时出现2秒的加载过程
      wx.showToast({
        title: 'loading',
        icon:'loading',
        duration:500
      });
      // 获取购物车列表
      this.getShoppingList();
      // 获取地址信息
      this.getAddressList();
      
    },
    
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
      //保存合计金额
      let sumPrice = this.data.sumPrice;
      wx.setStorageSync('sumPrice', sumPrice)
      console.log(this.data.shoppingList)
      console.log(wx.getStorageSync('cart')||[])
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
      this.changeIsCheckedFalse();
    },  

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
    
})